<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\controller\WeChatPay;
use app\common\model\MembershipCard;
use app\common\model\UserCardOrders;
use think\Db;
use think\Exception;

class Orders extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];

    protected array $params;

    public function __construct()
    {
        parent::__construct();
        $this->params = array_filter(array_merge($this->request->post(), $this->request->get()));
    }

    /**
     * 用户购买会员下单
     * @throws
     * */
    public function payMemberOrder()
    {
        $validate = $this->validate($this->params, 'app\\api\\validate\\User.payMemberOrder');
        if ($validate !== true) {
            $this->error($validate);
        }
        if (!$rows = MembershipCard::instance()->get(['id' => $this->params['cards_id']])) {
            $this->error('该购买会员不存在');
        }
        $condition['status'] = 2;
        $condition['user_id'] = $this->auth->id ?? 0;
        /*$condition['card_id'] = $this->params['cards_id'];*/
        $expire_date = date('Y-m-d H:i:s', strtotime('+' . $rows['month'] . ' month', strtotime(date('Y-m-d H:i:s'))));
        if ($orders = UserCardOrders::instance()->where($condition)->order('createtime DESC')->find()) {
            $expire_date = date('Y-m-d H:i:s', strtotime('+' . $rows['month'] . ' month', strtotime($orders['expire_date'])));
        }
        Db::startTrans();
        try {
            $save['card_id'] = $rows['id'];
            $save['user_id'] = $this->auth->id ?? 0;
            $save['order_sn'] = GetOrderSn();
            $save['money'] = $rows['sales_price'];
            $save['openid'] = $this->auth->openid;
            $save['params'] = json_encode($rows->toArray(), JSON_UNESCAPED_UNICODE);
            $save['expire_date'] = $expire_date;
            if (!floatval($rows['sales_price'])) {
                $save['status'] = 2;
                $save['params'] = json_encode($rows, JSON_UNESCAPED_UNICODE);
                $save['pay_time'] = date('Y-m-d H:i:s');
            }
            $response = UserCardOrders::instance()->allowField(true)->save($save);
            if ($response) {
                Db::commit();
                // 返回微信支付的调起参数
                if (floatval($rows['sales_price'])) {
                    $this->success('success', WeChatPay::instance($save)->weChatPay());
                }
                $this->success('success');
            }
            throw new Exception('下单失败');
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
    }
}